package com.example.treeHole.controller;

import com.example.treeHole.Annotation.Authority;
import com.example.treeHole.Enum.AuthorityEnum;
import com.example.treeHole.exception.CustomException;
import com.example.treeHole.result.Result;
import com.example.treeHole.service.UserService;
import com.example.treeHole.vo.UserInfo;
import com.example.treeHole.vo.VirtualCharacter;
import com.example.treeHole.vo.dto.UserInfoDto;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin//解决跨域问题
@RestController
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public Result<List<UserInfo>> getAll(){
        return Result.success(userService.getAll());
    }


    /**
     * 查询所有用户信息
     * @param UserInfo
     * @return
     */
    @GetMapping("/findBySearch")
    public Result<PageInfo<UserInfo>> findBySearch(UserInfoDto UserInfo){

        PageInfo<UserInfo> users = userService.findBySearch(UserInfo);
        return Result.success(users);
    }


    @PostMapping("/add")
    public Result<Integer> add (@RequestBody UserInfo userInfo){
        Integer add = userService.add(userInfo);
        if (add != 1){
            return Result.error("添加错误，请重试");
        }
        return Result.success(add);
    }

    @Authority(AuthorityEnum.TWO)
    @PostMapping("/delete/{userId}")
    public Result<Integer> delete(@PathVariable String userId){
        int delete = userService.delete(userId);
        return Result.success(delete);
    }

    @PostMapping("/update")
    public Result<Integer> update(@RequestBody UserInfo userInfo){
        int update = userService.update(userInfo);
        return Result.success(update);
    }

    @GetMapping("/findById/{userId}")
    public Result<UserInfo> findById(@PathVariable String userId){
        UserInfo userInfo=userService.findById(userId);
        return Result.success(userInfo);
    }

    @PostMapping("/login")
    public Result<UserInfo> login(@RequestBody UserInfo userInfo){
        UserInfo user =userService.login(userInfo);
        return Result.success(user);
    }

    @PostMapping("/switchover")
    public Result<VirtualCharacter> switchover(@RequestBody UserInfo userInfo){
        if (StringUtils.isEmpty(userInfo.getVirtuallyId() )||StringUtils.isEmpty(userInfo.getStatus()) ) {
            return Result.error("传参错误");
        }

        VirtualCharacter virtualCharacter=userService.switchover(userInfo);

        return Result.success(virtualCharacter);
    }

}
